package com.iwhalecloud.bss.kite.cucc.service.custview.evolve.task;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.CustViewBaseVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.CustViewVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.Fee;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.FeeInfoVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.HistoryFeeInfoVO;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.ztesoft.common.logger.api.ZLogger;
import com.ztesoft.common.logger.factory.ZLoggerFactory;

/**
 * @ClassName : FeeInfoTask
 * @Description : 资费信息
 * @Author : xie.zhengjun
 * @Date : 2021/4/30 19:22
 */
public class FeeInfoTask extends AbstractCustViewTask{
    private final ZLogger LOGGER = ZLoggerFactory.getLogger(this.getClass(), KeyConsts.LOG_MODULE);
    private static Map<String, Object> ATTR_DESC_MAP = null;

    static {
        ATTR_DESC_MAP = new HashMap<>();
        ATTR_DESC_MAP.put("200000106", "产品编码");
        ATTR_DESC_MAP.put("200000133", "协议资费");
        ATTR_DESC_MAP.put("200000169", "协议月租（元）");
        ATTR_DESC_MAP.put("200000170", "首月收取方式");
        ATTR_DESC_MAP.put("200000171", "末月收取方式");
        ATTR_DESC_MAP.put("200000172", "生效时间");
        ATTR_DESC_MAP.put("200000173", "失效时间");
        ATTR_DESC_MAP.put("200000174", "生效模式");
        ATTR_DESC_MAP.put("200000185", "包编码");
        ATTR_DESC_MAP.put("200001354", "标准月租（元）");
        ATTR_DESC_MAP.put("200002509", "价格（元）");
        ATTR_DESC_MAP.put("200003241", "包周期协议价（元）");
        ATTR_DESC_MAP.put("200003242", "包周期月数");
        ATTR_DESC_MAP.put("210004552", "到期后月租（元）");
        ATTR_DESC_MAP.put("210004553", "到期处理方式");
        ATTR_DESC_MAP.put("210004554", "是否收取违约金");
        ATTR_DESC_MAP.put("210004555", "违约金收取方式");
        ATTR_DESC_MAP.put("210004556", "违约金金额");
    }

    @Override
    public CustViewBaseVO call(Object[] args) {
        if (args.length != 2) {
            return null;
        }
        Map<String, Object> userDetail = (Map<String, Object>) args[0];
        CustViewVO custViewVO = (CustViewVO) args[1];

        FeeInfoVO feeInfoVO = new FeeInfoVO();
        HistoryFeeInfoVO historyFeeInfoVO = new HistoryFeeInfoVO();
        custViewVO.setFee(feeInfoVO);
        custViewVO.setHistoryFee(historyFeeInfoVO);

        //历史资费信息
        List<Fee> historyFeeList = new ArrayList<>();
        List<Fee> feeList = new ArrayList<>();

        if (KiteMapUtils.isNotEmpty(userDetail)) {
            List<Map<String, Object>> userDiscntInfos = (List<Map<String, Object>>) userDetail.get("USER_DISCNT_INFOS");
            if (KiteListUtils.isNotEmpty(userDiscntInfos)) {
                userDiscntInfos.forEach(userDiscntInfoMap -> {
                    Fee fee = new Fee();
                    String feecode=KiteMapUtils.getString(userDiscntInfoMap, "DISCNT_PRODUCT_ID");
                    fee.setFeeCode(feecode);
                    // 资费名称
                    String feeName = "";

                    String discntProductId = KiteMapUtils.getString(userDiscntInfoMap, "GOODS_ID");
                    if (KiteStringUtils.isNotEmpty(discntProductId)) {
                        Offer additionalOffer = OfferCache.get(discntProductId);
                        Map offerMap=additionalOffer.getOfferMap();
                        List<Map<String, Object>> productCategroys = (List<Map<String, Object>>) offerMap
                            .get("productCategroy");
                        for (Map productCategroy : productCategroys) {
                            String productType = KiteMapUtils.getString(productCategroy, "productType");
                            List<Map> products = (List<Map>) productCategroy.get("products");
                            if(!"pay".equals(productType)||KiteListUtils.isEmpty(products)) {
                                continue;
                            }
                            for (Map product : products) {
                                String productCode = KiteMapUtils.getString(product, "productCode");
                                if(feecode.equals(productCode)){
                                    feeName= KiteMapUtils.getString(product, "productName");

                                }
                            }
                        }
                    }

                    fee.setFeeName(feeName);
                    // 资费描述
                    String feeDesc = "";
                    // 资费属性
                    List<Map<String, Object>> userDiscntItemInfos = (List<Map<String, Object>>) userDiscntInfoMap.get("USER_DISCNT_ITEM_INFOS");
                    if (KiteListUtils.isNotEmpty(userDiscntItemInfos)) {
                        Map<String, String> attrMap = getAttrMap(userDiscntItemInfos);
                        feeDesc = getFeeDesc(attrMap);
                        fee.setAttrMap(transMap(attrMap));
                    }
                    fee.setFeeDesc(feeDesc);

                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    String startDate = KiteMapUtils.getString(userDiscntInfoMap, "START_DATE");
                    String endDate = KiteMapUtils.getString(userDiscntInfoMap, "END_DATE");
                    String updateDate = KiteMapUtils.getString(userDiscntInfoMap, "UPDATE_TIME");
                    Date start = null;
                    Date end = null;
                    Date upd = null;
                    try {
                        start = KiteStringUtils.isNotEmpty(startDate) ? simpleDateFormat.parse(startDate) : null;
                        end = KiteStringUtils.isNotEmpty(endDate) ? simpleDateFormat.parse(endDate) : null;
                        upd = KiteStringUtils.isNotEmpty(updateDate) ? simpleDateFormat.parse(updateDate) : null;
                    } catch (ParseException e) {
                        LOGGER.error(ErrorConsts.SYSTEM_ERROR.getErrorCode(), "格式化时间失败出错");
                        ErrorConsts.BUSI_COMMON_ERROR.throwOut("格式化时间失败");
                    }
                    fee.setStartDate(Objects.nonNull(start) ? KiteDateUtils.formatDate(start, KiteDateUtils.DATE_FORMAT) : null);
                    fee.setUpdateDate(Objects.nonNull(upd) ? KiteDateUtils.formatDate(upd, KiteDateUtils.DATE_FORMAT) : null);
                    if (end != null) {
                        fee.setEndDate(KiteDateUtils.formatDate(end, KiteDateUtils.DATE_FORMAT));
                        // 失效时间大于当日，则认为是资费信息；失效时间小于当日，则认为是历史资费信息。
                        long currentTimeMillis = KiteDateUtils.getCurrentTimeMillis();

                        long time = end.getTime();
                        if (currentTimeMillis > time) {
                            //历史资费信息
                            historyFeeList.add(fee);
                        } else {
                            //资费信息
                            feeList.add(fee);
                        }
                    }
                });

                feeInfoVO.setFees(feeList);
                historyFeeInfoVO.setFees(historyFeeList);
            }
        }
        return feeInfoVO;
    }

    /**
     * 翻译资费属性
     *
     * @param userDiscntItemInfos 资费属性map
     * @return 翻译后的资费属性map
     */
    public static Map<String, String> getAttrMap(List<Map<String, Object>> userDiscntItemInfos) {
        Map<String, String> attrMap = new HashMap<>();
        for (Map<String, Object> userDiscntItemInfo : userDiscntItemInfos) {
            String crmAttrCode = KiteMapUtils.getString(userDiscntItemInfo, "CRM_ATTR_CODE");
            String crmAttrValue = KiteMapUtils.getString(userDiscntItemInfo, "CRM_ATTR_VALUE");

            String attrValue = "";
            switch (crmAttrCode) {
                case "200000106":
                    //产品编码
                    attrMap.put("200000106", crmAttrValue);
                    break;
                case "200000133":
                    //协议资费
                    attrMap.put("200000133", crmAttrValue);
                    break;
                case "200000169":
                    //协议月租（元）
                    attrMap.put("200000169", crmAttrValue);
                    break;
                case "200000170":
                    //首月收取方式
                    attrValue = Optional.ofNullable(AttrValueCache.getAttrValue("202012150004", crmAttrValue))
                        .map(AttrValue::getAttrValueName).orElse(crmAttrValue);
                    attrMap.put("200000170", attrValue);
                    break;
                case "200000171":
                    //末月收取方式
                    attrValue = Optional.ofNullable(AttrValueCache.getAttrValue("202012150005", crmAttrValue))
                        .map(AttrValue::getAttrValueName).orElse(crmAttrValue);
                    attrMap.put("200000171", attrValue);
                    break;
                case "200000172":
                    //生效时间
                    attrMap.put("200000172", crmAttrValue);
                    break;
                case "200000173":
                    //失效时间
                    attrMap.put("200000173", crmAttrValue);
                    break;
                case "200000174":
                    //生效模式
                    attrValue = Optional.ofNullable(AttrValueCache.getAttrValue("202012150224", crmAttrValue))
                        .map(AttrValue::getAttrValueName).orElse(crmAttrValue);
                    if("110007643".equals(crmAttrValue)){
                        attrValue="一次性资费";
                    }
                    attrMap.put("200000174", attrValue);
                    break;
                case "200000185":
                    //包编码
                    attrMap.put("200000185", crmAttrValue);
                    break;
                /*case "200001735":
                    //失效模式
                    attrMap.put("失效模式", crmAttrValue);
                    break;*/
                case "200001354":
                    //标准月租（元）
                    attrMap.put("200001354", crmAttrValue);
                    break;
                case "200002509":
                    //价格（元）
                    attrMap.put("200002509", crmAttrValue);
                    break;
                case "200003241":
                    // 包周期协议价（元）
                    attrMap.put("200003241", crmAttrValue);
                    break;
                case "200003242":
                    // 包周期月数
                    attrMap.put("200003242", crmAttrValue);
                    break;
                case "210004552":
                    // 到期后月租（元）
                    attrMap.put("210004552", crmAttrValue);
                    break;
                case "210004554":
                    // 是否收取违约金
                    attrValue = Optional.ofNullable(AttrValueCache.getAttrValue("2020000005", crmAttrValue))
                        .map(AttrValue::getAttrValueName).orElse(crmAttrValue);
                    attrMap.put("210004554", attrValue);
                    break;
                case "210004555":
                    // 违约金收取方式
                    attrValue = KiteStringUtils.equals(crmAttrValue, "110007675") ? "人工录入" : (KiteStringUtils.equals(crmAttrValue, "110007676") ? "系统计算" : "");
                    attrMap.put("210004555", attrValue);
                    break;
                case "210004556":
                    // 违约金金额
                    attrMap.put("210004556", crmAttrValue);
                    break;
                default:
                    break;
            }
        }
        return attrMap;
    }

    private String getFeeDesc(Map<String, String> attrMap) {
        StringBuffer feeDescribe = new StringBuffer();
        DcPublic feeAttrConfig = DcPublicCache.get("2021007061", "feeDescAttrConfig");
        if (Objects.nonNull(feeAttrConfig) && Objects.nonNull(feeAttrConfig.getCodea())) {
            String[] feeAttrs = feeAttrConfig.getCodea().split(",");
            for (int i = 0; i < feeAttrs.length; i++) {
                String value = KiteMapUtils.getStrValue(attrMap, feeAttrs[i]);
                if (KiteStringUtils.isNotEmpty(value)) {
                    feeDescribe.append(KiteMapUtils.getStrValue(ATTR_DESC_MAP, feeAttrs[i])).append("=").append(value).append(";");
                }
            }
        } else {
            Iterator<String> iterator = attrMap.keySet().iterator();
            while (iterator.hasNext()) {
                String fieldName = String.valueOf(iterator.next());
                String value = KiteMapUtils.getStrValue(attrMap, fieldName);
                feeDescribe.append(KiteMapUtils.getStrValue(ATTR_DESC_MAP, fieldName)).append("=").append(value).append(";");
            }
        }
        return feeDescribe.toString();
    }

    public static Map<String, String> transMap(Map<String, String> attrMap) {
        Map<String, String> resMap = new HashMap<>();
        Iterator<String> iterator = attrMap.keySet().iterator();
        while (iterator.hasNext()) {
            String fieldName = String.valueOf(iterator.next());
            String value = KiteMapUtils.getStrValue(attrMap, fieldName);
            resMap.put(KiteMapUtils.getString(ATTR_DESC_MAP, fieldName), value);
        }
        return resMap;
    }
}
